<template>
  <div class="route-drawing-app">
    <!-- 顶部操作栏 -->
    <el-row class="operation-bar">
      <el-col :span="16">
        <!-- 路线信息 -->
        <div class="route-info" v-if="hasRoutePoints">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="点数">{{ routePoints.length }} 个</el-descriptions-item>
            <el-descriptions-item label="路线长"
              >{{ routeLength.toFixed(2) }} 米</el-descriptions-item
            >
            <el-descriptions-item label="更新">{{ lastEditTime }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <!-- 操作提示 -->
        <el-alert
          v-if="isDrawing"
          title="绘制模式：点击地图添加点，拖动点可调整位置，点击结束绘制按钮完成"
          type="info"
          :closable="false"
        />
      </el-col>
      <el-col :span="8" class="button-group">
        <el-button type="primary" @click="toggleDrawingMode">
          {{ isDrawing ? '结束绘制' : '开始绘制' }}
        </el-button>
        <el-button type="success" @click="showSaveDialog" :disabled="!hasRoutePoints || isDrawing">
          保存路线
        </el-button>
        <el-button type="danger" @click="clearRoute" :disabled="!hasRoutePoints">
          清除路线
        </el-button>
      </el-col>
    </el-row>
    <div class="flex justify-around h-full">
      <!-- 地图容器 -->
      <div id="map-container" class="map-container"></div>

      <!-- 路线列表 -->
      <el-card class="route-list-card" shadow="hover" style="margin-top: 12px">
        <div class="list-header">
          <span>路线列表</span>
          <div>
            <el-button size="small" @click="fetchRouteList" :loading="listLoading">刷新</el-button>
          </div>
        </div>
        <el-table
          :data="routeList"
          v-loading="listLoading"
          empty-text="暂无数据"
          height="650"
          @row-click="handleRowClick"
        >
          <el-table-column type="index" label="#" width="60" />
          <el-table-column prop="name" label="名称" min-width="180" />
          <el-table-column label="点数" width="100">
            <template #default="{ row }">
              {{ Array.isArray(row?.route) ? row.route.length : 0 }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEditRoute(row)">编辑</el-button>
              <el-button type="danger" link @click="handleDeleteRoute(row)">删除</el-button>
              <el-button type="success" link @click="handleSendCommand(row)">下发指令</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <!-- 下发指令对话框 -->
    <el-dialog title="下发路线指令" v-model="sendDialogVisible" width="500px">
      <el-form :model="sendForm" ref="sendFormRef" :rules="sendFormRules" label-width="100px">
        <el-form-item label="机器人MAC" prop="robotMac" label-width="100px">
          <el-input
            v-model="sendForm.robotMac"
            placeholder="请输入机器人MAC地址,如:12:34:56:78:90:AB"
          ></el-input>
        </el-form-item>
        <el-form-item label="路线名称">
          <el-input v-model="sendForm.route.name" readonly></el-input>
        </el-form-item>
        <el-form-item label="路线ID">
          <el-input v-model="sendForm.route.id" readonly></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="sendDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSendCommand">确认下发</el-button>
      </template>
    </el-dialog>

    <!-- 保存对话框 -->
    <el-dialog title="保存路线" v-model="saveDialogVisible" width="500px">
      <el-form :model="routeForm" ref="routeFormRef" :rules="formRules" label-width="80px">
        <el-form-item label="路线名称" prop="name">
          <el-input v-model="routeForm.name" placeholder="请输入路线名称"></el-input>
        </el-form-item>
        <el-form-item label="路线坐标">
          <el-input
            :model-value="formattedRoutePoints"
            type="textarea"
            :rows="6"
            readonly
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="saveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRoute">确认保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, watch, computed } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
// import { PenLine, Stop, Save, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElAlert, ElMessageBox } from 'element-plus'

import { useUserStore } from '@/store/user'
import {
  getRouteList,
  addRoute,
  updateRoute,
  deleteRoute,
  getOneRoute,
  sendRouteCommand
} from '@/api/settings'

/**
 * 路線點位
 */
type RoutePoint = {
  id: number
  x: number // 緯度
  y: number // 經度
}

const currentEditingRouteId = ref<number | null>(null) // 当前编辑的路线ID
const isViewingRoute = ref<boolean>(false) // 是否处于查看路线模式

// 地图核心对象
const map = ref<any>(null)
const polyline = ref<any>(null) // 当前路线折线实例
const markers = ref<any[]>([]) // 点标记实例数组
const isDrawing = ref<boolean>(false) // 是否处于绘制模式

// 路线数据
const routePoints = ref<RoutePoint[]>([]) // 存储格式: [{x: 纬度, y: 经度, id: 唯一标识}, ...]
const routeLength = ref<number>(0) // 路线总长度(米)
const lastEditTime = ref<string>('')

// 表单相关
const saveDialogVisible = ref<boolean>(false)
const routeForm = reactive<{ name: string; route: string }>({
  name: '',
  route: ''
})
const routeFormRef = ref<any>(null)
const formRules = {
  name: [
    { required: true, message: '请输入路线名称', trigger: 'blur' },
    { min: 2, max: 50, message: '名称长度在 2-50 字符', trigger: 'blur' }
  ]
}

// 下发指令相关
const sendDialogVisible = ref<boolean>(false)
const sendForm = reactive({
  robotMac: '',
  route: {
    id: 0,
    name: '',
    route: [] as Array<{ x: number; y: number }>,
    userId: 0
  }
})
const sendFormRef = ref<any>(null)
const sendFormRules = {
  robotMac: [
    { required: true, message: '请输入机器人MAC地址', trigger: 'blur' },
    {
      pattern: /^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$/,
      message: '请输入有效的MAC地址,如:12:34:56:78:90:AB格式',
      trigger: 'blur'
    }
  ]
}

// 计算属性
const hasRoutePoints = computed(() => routePoints.value.length > 0)
// 计算属性：生成 [{'x': ..., 'y': ...}] 格式的字符串
const formattedRoutePoints = computed(() => {
  const pointArray = routePoints.value.map((p) => ({
    x: p.x, // 确保键为小写x
    y: p.y // 确保键为小写y
  }))

  // 2. 转换为标准JSON格式的数组字符串（键为双引号，整体为字符串）
  return JSON.stringify(pointArray)
})

// 路线列表（表格）
const routeList = ref<any[]>([])
const listLoading = ref<boolean>(false)

const fetchRouteList = async () => {
  try {
    listLoading.value = true
    const res: any = await getRouteList()
    // 兼容不同返回结构
    const data = Array.isArray(res?.data.list) ? res.data.list : Array.isArray(res) ? res : []
    routeList.value = data
  } catch (error) {
    console.error('获取路线列表失败:', error)
    ElMessage.error('获取路线列表失败')
  } finally {
    listLoading.value = false
  }
}

const handleDeleteRoute = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确认删除路线 "${row?.name ?? ''}" 吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '删除',
      cancelButtonText: '取消'
    })
  } catch {
    return
  }

  try {
    await deleteRoute(Number(row?.id))
    ElMessage.success('删除成功')
    fetchRouteList()
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败，请重试')
  }
}

// 初始化地图
/**
 * 初始化地圖並綁定事件
 */
const initMap = () => {
  AMapLoader.load({
    key: 'e0984a53cef2fad7a477dafd7b777751', // 替换为实际密钥
    version: '2.0',
    plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.GeometryUtil']
  })
    .then((AMap) => {
      // 初始化地图实例
      map.value = new AMap.Map('map-container', {
        zoom: 13,
        center: [116.4074, 39.9042], // [经度, 纬度]
        resizeEnable: true
      })

      // 添加控件
      map.value.addControl(new AMap.ToolBar({ position: 'RB' }))
      map.value.addControl(new AMap.Scale({ position: 'LB' }))

      // 绑定地图点击事件（核心：手动控制点添加，替代DrawManager）
      map.value.on('click', handleMapClick)

      ElMessage.success('地图加载完成')
    })
    .catch((error) => {
      console.error('地图初始化失败:', error)
      ElMessage.error('地图加载失败，请检查API密钥')
    })
}

// 地图点击事件处理（绘制模式下添加点）
const handleMapClick = (e: any) => {
  if (!isDrawing.value) return

  // 获取点击位置坐标 [经度, 纬度]
  const { lng, lat } = e.lnglat

  // 创建点数据（带唯一标识）
  const point = {
    id: Date.now(), // 用时间戳作为临时唯一ID
    x: lat, // 纬度
    y: lng // 经度
  }

  // 添加到路线数组
  routePoints.value.push(point)

  // 更新地图元素（标记和折线）
  updateMapElements()

  // 更新路线信息
  updateRouteInfo()
}

// 更新地图元素（标记点和折线）
const updateMapElements = () => {
  if (!map.value) return

  // 1. 清除现有标记和折线
  clearMapElements(false)

  // 2. 创建新标记点
  const AMap = window.AMap
  routePoints.value.forEach((point, index) => {
    const marker = new AMap.Marker({
      position: [point.y, point.x], // [经度, 纬度]
      anchor: 'bottom-center',
      draggable: true, // 允许拖拽（核心交互）
      // 自定义点标记内容（显示序号）
      content: `<div class="custom-marker">${index + 1}</div>`,
      zIndex: 100
    })

    // 绑定拖拽事件（实时更新坐标）
    marker.on('dragend', (e: any) => {
      const { lng, lat } = e.lnglat
      const target = routePoints.value.find((p) => p.id === point.id)
      if (target) {
        target.x = lat
        target.y = lng
        updateRouteInfo()
        drawPolyline()
        ElMessage.success('已更新点坐标') // 添加反馈提示
      }
    })

    // 添加到地图和标记数组
    map.value.add(marker)
    markers.value.push(marker)
  })

  // 3. 绘制折线
  drawPolyline()
}

// 绘制折线
const drawPolyline = () => {
  if (!map.value || routePoints.value.length < 2) return

  const AMap = window.AMap
  // 转换坐标格式为 [经度, 纬度] 数组
  const path = routePoints.value.map((p) => [p.y, p.x])

  // 创建或更新折线
  if (polyline.value) {
    polyline.value.setPath(path)
  } else {
    polyline.value = new AMap.Polyline({
      path,
      strokeColor: '#36BFFA',
      strokeWeight: 6,
      strokeOpacity: 0.8,
      zIndex: 50
    })
    map.value.add(polyline.value)
  }
}

// 更新路线信息（长度和时间）
const updateRouteInfo = () => {
  if (routePoints.value.length < 2) {
    routeLength.value = 0
    return
  }

  // 计算路线总长度（使用高德几何工具）
  const AMap = window.AMap
  let totalLength = 0
  for (let i = 0; i < routePoints.value.length - 1; i++) {
    const p1 = routePoints.value[i]
    const p2 = routePoints.value[i + 1]
    // 计算两点间距离（米）
    totalLength += AMap.GeometryUtil.distance(
      [p1.y, p1.x], // [经度, 纬度]
      [p2.y, p2.x]
    )
  }
  routeLength.value = totalLength
  lastEditTime.value = new Date().toLocaleString()
}

// 切换绘制模式
const toggleDrawingMode = () => {
  isDrawing.value = !isDrawing.value
  if (isDrawing.value) {
    ElMessage.info('已进入绘制模式，点击地图添加路线点')
  } else {
    ElMessage.info('已退出绘制模式')
  }
}

// 清除路线
const clearRoute = () => {
  // 清除地图元素
  clearMapElements(true)
  // 重置数据
  routePoints.value = []
  routeLength.value = 0
  routeForm.route = ''
  routeForm.name = ''
  currentEditingRouteId.value = null // 重置编辑ID
  isViewingRoute.value = false
  ElMessage.success('路线已清除')
}

// 清除地图元素（标记和折线）
const clearMapElements = (clearData = false) => {
  if (map.value) {
    // 移除标记
    if (markers.value.length) {
      map.value.remove(markers.value)
      markers.value = []
    }
    // 移除折线
    if (polyline.value) {
      map.value.remove(polyline.value)
      polyline.value = null
    }
  }
}

// 显示保存对话框
const showSaveDialog = () => {
  if (routePoints.value.length < 2) {
    ElMessage.warning('至少需要2个点才能形成路线')
    return
  }
  routeForm.route = formattedRoutePoints.value
  saveDialogVisible.value = true
}

// 提交路线数据
/**
 * 送出路線資料
 */
const submitRoute = () => {
  routeFormRef.value
    .validate()
    .then(() => {
      const userStore = useUserStore()
      const submitData = {
        name: routeForm.name,
        route: JSON.parse(routeForm.route || '[]'),
        userId: Number(userStore.userId)
      }

      // 根据是否有编辑ID判断是新增还是更新
      if (currentEditingRouteId.value) {
        return updateRoute({ ...submitData, id: currentEditingRouteId.value })
      } else {
        return addRoute(submitData)
      }
    })
    .then(() => {
      ElMessage.success(currentEditingRouteId.value ? '路线更新成功' : '路线保存成功')
      saveDialogVisible.value = false
      clearRoute()
      fetchRouteList()
    })
    .catch((error: any) => {
      console.error('保存失败:', error)
      if (error?.name !== 'ValidationError') {
        ElMessage.error('保存失败，请重试')
      }
    })
}

// 行点击显示路线
const handleRowClick = async (row: any) => {
  try {
    // 加载路线详情
    const res: any = await getOneRoute(Number(row.id))
    const routeData = res.data
    // 解析路线坐标（处理单引号转双引号问题）
    // const routePointsArray = JSON.parse(routeData.route.replace(/'/g, '"'))

    // 转换为本地路线点格式
    routePoints.value = routeData.route.map((p: any, index: number) => ({
      id: Date.now() + index, // 生成临时唯一ID
      x: p.x,
      y: p.y
    }))

    // 更新地图显示
    updateMapElements()
    // 更新路线信息
    updateRouteInfo()
    // 切换到查看模式
    isDrawing.value = false
    isViewingRoute.value = true
    currentEditingRouteId.value = null
  } catch (error) {
    console.error('获取路线详情失败:', error)
    ElMessage.error('获取路线详情失败')
  }
}

// 编辑路线
const handleEditRoute = async (row: any) => {
  try {
    const res: any = await getOneRoute(Number(row.id))
    const routeData = res.data

    // 解析路线坐标
    // const routePointsArray = JSON.parse(routeData.route.replace(/'/g, '"'))

    // 转换为本地路线点格式
    routePoints.value = routeData.route.map((p: any, index: number) => ({
      id: Date.now() + index,
      x: p.x,
      y: p.y
    }))

    // 更新地图显示
    updateMapElements()
    // 更新路线信息
    updateRouteInfo()
    // 进入编辑模式
    isDrawing.value = true
    isViewingRoute.value = false
    // 记录当前编辑的路线ID
    currentEditingRouteId.value = routeData.id
    // 填充表单名称
    routeForm.name = routeData.name
  } catch (error) {
    console.error('获取路线详情失败:', error)
    ElMessage.error('获取路线详情失败')
  }
}

// 打开下发指令对话框
const handleSendCommand = (row: any) => {
  // 填充路线信息
  sendForm.robotMac = ''
  sendForm.route = {
    id: row.id,
    name: row.name,
    route: row.route,
    userId: Number(useUserStore().userId)
  }
  sendDialogVisible.value = true
}

// 提交下发指令
const submitSendCommand = () => {
  sendFormRef.value
    .validate()
    .then(async () => {
      try {
        // 发送指令
        await sendRouteCommand({
          robotMac: sendForm.robotMac,
          route: {
            route: sendForm.route.route || [],
            name: sendForm.route.name,
            userId: sendForm.route.userId
          }
        })
        ElMessage.success('指令下发成功')
        sendDialogVisible.value = false
      } catch (error) {
        console.error('指令下发失败:', error)
        ElMessage.error('指令下发失败，请重试')
      }
    })
    .catch((error) => {
      console.error('表单验证失败:', error)
    })
}

// 监听路线点变化，同步更新表单路线数据
watch(routePoints, () => {
  if (hasRoutePoints.value) {
    routeForm.route = formattedRoutePoints.value
  }
})

// 组件挂载时初始化地图
onMounted(() => {
  initMap()
  fetchRouteList()
})
</script>

<style scoped lang="scss">
.route-drawing-app {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 16px;
  box-sizing: border-box;
  background-color: #f5f7fa;
}

.operation-bar {
  // margin-bottom: 16px;
  // padding-bottom: 16px;
  // border-bottom: 1px solid #e5e7eb;
}

.button-group {
  text-align: right;
}

.button-group :deep(.el-button) {
  margin-left: 8px;
}

.map-container {
  margin-top: 2px;
  height: 100%;
  width: 90%;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-right: 8px;
}

.route-info {
  // margin-top: 4px;
  // padding: 5px;
  /* background-color: #fff; */
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

h1 {
  margin: 0;
  font-size: 20px;
  color: #1f2329;
}

/* 自定义点标记样式 */
.custom-marker {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  text-align: center;
  line-height: 24px;
  font-size: 14px;
  border: 2px solid white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.route-list-card .list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  font-weight: 600;
}
</style>
